package com.zhen.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 网页转图片处理类，使用外部CMD
 */
public class PhantomTools {


    private static final String _tempPath = "D:/data/temp/phantom_";
    private static final String _shellCommand1 = "D:/xuexi/workspace_springCloud/spring-test/src/main/resources/phantomjs-2.1.1-windows/bin/phantomjs.exe ";// 插件引入地址
    private static final String _shellCommand2 = "D:/xuexi/workspace_springCloud/spring-test/src/main/resources/phantomjs-2.1.1-windows/examples/rasterize.js ";// js引入地址
/*    private static final String _shellCommand1 = "phantomjs ";
    private static final String _shellCommand2 = "rasterize.js ";
*/
    private String _file;
    private String _size;

    /**
     * 构造截图类
     * @param hash 用于临时文件的目录唯一化
     * @param basePath phantomJs所在路径
     */
    public PhantomTools(int hash) {
        _file = _tempPath + hash + ".png";
    }

    /**
     * 构造截图类
     * @param hash 用于临时文件的目录唯一化
     * @param size 图片的大小，如800px*600px（此时高度会裁切），或800px（此时 高度最少=宽度*9/16，高度不裁切）
     * @param basePath phantomJs所在路径
     */
    public PhantomTools(int hash, String size) {
        _file = _tempPath + hash + ".png";
        if (size != null)
            _size = " " + size;
    }

    /**
     * 将目标网页转为图片字节流
     * @param url 目标网页地址
     * @return 字节流
     */
    public byte[] getByteImg(String url) throws IOException {
        BufferedInputStream in = null;
        ByteArrayOutputStream out = null;
        File file = null;
        byte[] ret = null;
        try {
            if (exeCmd( _shellCommand1  + _shellCommand2 + url + " " + _file /*+ (_size != null ? _size : "")*/)) {
                file = new File(_file);
                if (file.exists()) {
                    out = new ByteArrayOutputStream();
                    byte[] b = new byte[5120];
                    in = new BufferedInputStream(new FileInputStream(file));
                    int n;
                    while ((n = in.read(b, 0, 5120)) != -1) {
                        out.write(b, 0, n);
                    }
                    file.delete();
                    ret = out.toByteArray();
                }
            } else {
                ret = new byte[] {};
            }
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        return ret;
    }

    /**
     * 执行CMD命令
     */
    private static boolean exeCmd(String commandStr) {
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            if (p.waitFor() != 0 && p.exitValue() == 1) {
                return false;
            }
        } catch (Exception e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
        }
        return true;
    }
}
